package ink.wbc.aviator;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDouble;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wbc
 * @date 2021/9/16
 * @desc
 */
public class AviatorMain {

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>(8);
        map.put("money", "200");
        System.out.println(AviatorEvaluator.execute("'充值金额: '+ money", map));

        // 注册自定义函数
        AviatorEvaluator.addFunction(new AddFunction());
        System.out.println(AviatorEvaluator.execute("add(100, 2003)"));

        Map<String, Object> param = new HashMap<>(3);
        param.put("a", 100);
        param.put("b", 200);
        param.put("c", 300);
        System.out.println(customizeExpression(param));
    }


    static class AddFunction extends AbstractFunction {
        @Override
        public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
            double num1 = FunctionUtils.getNumberValue(arg1, env).doubleValue();
            double num2 = FunctionUtils.getNumberValue(arg2, env).doubleValue();
            return new AviatorDouble(num1 + num2);
        }

        @Override
        public String getName() {
            return "add";
        }
    }

    /**
     * 自定义表达式
     *
     * @param param
     * @return
     */
    public static Object customizeExpression(Map<String, Object> param) {
        String expression = "a+(b*c)";
        // 编译表达式
        Expression compiledExp = AviatorEvaluator.compile(expression);
        return compiledExp.execute(param);
    }

}
